package com.hwd.gmall.seckill.controller;

import com.hwd.gmall.common.constant.SeckillConst;
import com.hwd.gmall.common.result.Result;
import com.hwd.gmall.common.util.MyThreadLocal;
import com.hwd.gmall.seckill.pojo.UserRecode;
import com.hwd.gmall.seckill.service.SeckillGoodsService;
import com.hwd.gmall.seckill.service.SeckillOrderService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 黄伟东/Victor
 * @date 2022/5/11 19:56
 */
@RestController
@RequestMapping(value = "/seckill/goods")
public class SeckillOrderController {

    @Resource
    private SeckillOrderService seckillOrderService;

    @Resource
    private SeckillGoodsService seckillGoodsService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 秒杀下单：排队
     *
     * @param startTime 指定时间段
     * @param goodsId   商品id
     * @param num       下单数量
     * @return com.hwd.gmall.common.result.Result<com.hwd.gmall.seckill.pojo.UserRecode>
     */
    @GetMapping(value = "/addSeckillOrder")
    public Result<UserRecode> addSeckillOrder(String startTime, String goodsId, Integer num) {
        return Result.ok(seckillOrderService.addSeckillOrder(startTime, goodsId, num));
    }

    /**
     * 查询用户的排队状态，即下单状态
     *
     * @return com.hwd.gmall.common.result.Result<com.hwd.gmall.seckill.pojo.UserRecode>
     */
    @GetMapping(value = "/getUserRecode")
    public Result<UserRecode> getUserRecode() {
        return Result.ok(seckillOrderService.getUserRecode());
    }

    /**
     * 测试
     *
     * @param time 指定时间段
     * @return com.hwd.gmall.common.result.Result<java.lang.Void>
     */
    @GetMapping(value = "/test")
    public Result<Void> test(String time) {
        seckillGoodsService.mergeSeckillGoodsStockFromRedisToDb(time);
        return Result.ok();
    }


    /**
     * 主动取消订单
     *
     * @param orderId 订单id
     */
    @GetMapping(value = "/cancelSeckillOrder")
    public Result<Void> cancelSeckillOrder(String orderId) {
        // 防止并发重复取消订单
        Long increment = redisTemplate
                .opsForValue().increment(SeckillConst.USER_SECKILL_ORDER_CANCEL_COUNT + MyThreadLocal.get(), 1);
        try {
            if (increment != null && increment == 1) {
                seckillOrderService.cancelSeckillOrder(orderId, MyThreadLocal.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisTemplate.delete(SeckillConst.USER_SECKILL_ORDER_CANCEL_COUNT + MyThreadLocal.get());
        }
        return Result.ok();
    }
}
